import 'dart:ffi';

import 'package:flutter/material.dart';
import 'dart:async';

class StreamHomeDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title:Text('StreamHomeDemo'),
          elevation: 0.0,
        ),
        body:StreamDemo(),
    );
  }
}

class StreamDemo extends StatefulWidget {
  @override
  _StreamDemoState createState() => _StreamDemoState();
}

class _StreamDemoState extends State<StreamDemo> {
  StreamSubscription _streamSubscription;
  StreamController<String>_streamDemo ;
  StreamSink _sinkDemo;
  String streamData = '......';

  @override
  void dispose() {
    // TODO: implement dispose
    _streamDemo.close();
    super.dispose();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //_streamDemo = Stream.fromFuture(FetchData());
    _streamDemo = StreamController.broadcast();
    _sinkDemo = _streamDemo.sink;
    _streamSubscription = _streamDemo.stream.listen(onData,onError:onError,onDone:onDone);
    _streamSubscription = _streamDemo.stream.listen(onDataTwo,onError:onError,onDone:onDone);
  }
  
  void onDone(){
    print('onDone');
  }

  void onError(error){
    print('$error');
  }
void onDataTwo(String data){
     print('onDataTwo----->$data');
}
  void onData(String data){
    setState(() {
       streamData = data;
    });
    print('$data');
  }
  Future<String> FetchData() async{
    await Future.delayed(Duration(seconds:5));
    return 'hello ~';
  }

  Void _pause(){

     _streamSubscription.pause();
  }
  Void _start(){
     _streamSubscription.resume();
  }
  Void _cancel(){
    _streamSubscription.cancel();
  }
  Future<String> _addStream() async{
    String data = await FetchData();
    //_streamDemo.add(data);
    _sinkDemo.add(data);
  }
  @override
  Widget build(BuildContext context) {
    return Container(
       child:Center(
         child:Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
           StreamBuilder(
             stream: _streamDemo.stream,
             builder: (context, snapshot){
               return Text('${snapshot.data}');
             },
           ),
            SizedBox(height:10),
            Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children:<Widget>[
              FlatButton(
                 onPressed: _addStream,
                  child: Text('添加')
                 ),
               FlatButton(
                 onPressed: _pause,
                  child: Text('暫停')
                 ),
                 FlatButton(
                 onPressed: _start,
                  child: Text('開始')
                 ),
                 FlatButton(
                 onPressed: _cancel,
                  child: Text('取消')
                 )
            ]
          ),
          ]
         )
          ),
    );
  }
}

